/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2022-2022. All rights reserved.
 *
 */

import { TaskDetails } from '@ohos/hvigor';
import fse from 'fs-extra';
import path from 'path';

import { CommonConst } from '../const/common-const.js';
import { JsonProfile } from '../model/json-profile.js';
import { checkArrayElementIsSame } from '../utils/array-util.js';
import { getJson5Obj } from '../utils/json-util.js';
import { OhosLogger } from '../utils/log/ohos-logger.js';

import { SyscapJsonObj } from './abstract/abstract-syscap-transform.js';
import { TargetTaskService } from './service/target-task-service.js';
import { OhosHapTask } from './task/ohos-hap-task.js';

/**
 * syscap相关配置预检查任务
 */
export class PreCheckSyscap extends OhosHapTask {
  private _log = OhosLogger.getLogger(PreCheckSyscap.name);
  private readonly sysCapJsonPath: string;
  private readonly sourceRoot: string;
  private readonly jsonFilePath: string;

  constructor(targetTaskService: TargetTaskService, taskDetails: TaskDetails) {
    super(targetTaskService, taskDetails);
    const targetName = targetTaskService.getTargetData().getTargetName();
    this.sourceRoot = this.service.getModuleModel()?.getSourceRootByTargetName(targetName);
    this.jsonFilePath = path.resolve(this.sourceRoot, this.service.isFaMode() ? CommonConst.CONFIG_JSON : CommonConst.MODULE_JSON5);
    this.sysCapJsonPath = path.resolve(this.sourceRoot, CommonConst.SYSCAP_JSON);
  }

  protected doTaskAction(): void {
    if (this.targetData.isHarmonyOS()) {
      return;
    }
    const jsonProfileByModel: JsonProfile = this.moduleModel.getJsonProfileByModel(this.service, this.targetName);
    if (jsonProfileByModel.deviceTypes.length === 0 && !fse.existsSync(this.sysCapJsonPath)) {
      this._log.printErrorExit(
        'JSON_PROFILE_MISSING',
        [this.moduleName, CommonConst.SYSCAP_JSON, CommonConst.PCID_SC, this.jsonFilePath],
        [[CommonConst.MODULE_JSON5, this.moduleName, CommonConst.PCID_SC]],
      );
    }

    if (fse.existsSync(this.sysCapJsonPath)) {
      const sysCapJsonObj: SyscapJsonObj = getJson5Obj(this.sysCapJsonPath);
      const generalSysCapList = sysCapJsonObj.devices.general;
      if (jsonProfileByModel.deviceTypes.length === 0) {
        // 纯N设备场景 若syscap.json中general字段存在且不为空则校验报错
        if (generalSysCapList && generalSysCapList.length !== 0) {
          this._log.printErrorExit(
            'SYSCAP_FIELD_NOT_EMPTY',
            [
              CommonConst.DEVICES_GENERAL,
              CommonConst.SYSCAP_JSON,
              jsonProfileByModel.deviceConfig,
              this.moduleName,
              jsonProfileByModel.configurationProfile,
              this.sysCapJsonPath,
            ],
            [[CommonConst.DEVICES_GENERAL, CommonConst.SYSCAP_JSON, jsonProfileByModel.deviceConfig, this.moduleName, jsonProfileByModel.configurationProfile]],
          );
        }
      } else {
        // 1+8设备场景,config.json/module.json5中deviceType不为空
        // 若syscap.json中general不存在或general字段配置与deviceType字段配置不一致则校验报错
        if (!generalSysCapList || !checkArrayElementIsSame(generalSysCapList, jsonProfileByModel.deviceTypes)) {
          this._log.printErrorExit(
            'DEVICE_TYPE_NOT_INCONSISTENT',
            [CommonConst.DEVICES_GENERAL, this.sysCapJsonPath],
            [[CommonConst.DEVICES_GENERAL, CommonConst.SYSCAP_JSON, jsonProfileByModel.deviceConfig, this.moduleName, jsonProfileByModel.configurationProfile]],
          );
        }
      }
    }
  }

  public initTaskDepends(): void {
    // no depends
  }
}
